import { Component, OnInit, EventEmitter } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { BehaviorSubject } from "rxjs/BehaviorSubject";

import { TableTab, TableHeader } from "../f10-shared/interface-shared";
import { scroll } from "../f10-shared/common-methods";
import { removeHMS, compare, handleVal, replaceUnit, optimizeUnit } from "../f10-shared/util";
import { F10Service } from "../service/f10.service";

// f1o util
import { basicChartColors } from "../f10-shared/util";

@Component({
  templateUrl: 'main-indicator.component.html',
  styleUrls: ['main-indicator.component.less']
})
export class MainIndicatorComponent implements OnInit {
  timer = null;
  subLists: TableTab[] = [
    {
      label: "主要指标",
      class: 'sub-title-0'
    }
  ]
  // 股票代码Observable
  routerParamsStream: Observable<any>;
  // 季报tab切换
  reportsCycle: TableTab[] = [
    {
      label: '全部',
      class: 'all'
    },
    {
      label: '一季报',
      class: '03'
    },
    {
      label: '中报',
      class: '06'
    },
    {
      label: '三季报',
      class: '09'
    },
    {
      label: '年报',
      class: '12'
    },
  ]
  reportsDict = {
    'all': '全部',
    '12': '年报',
    '09': '三季报',
    '06': '中报',
    '03': '一季报',
  }
  indicatorHeader: TableHeader[] = [
    {
      format: false,
      label: `指标\\日期`,
      key: 'EndDate'
    },
    {
      format: false,
      label: `主要指标`,
      key: '$type'
    },
    {
      format: true,
      label: `市盈率`,
      key: 'PE',
      clickEmitter: true
    },
    {
      format: true,
      label: `市净率`,
      key: 'PB',
      clickEmitter: true
    },
    {
      format: true,
      label: `每股收益`,
      key: 'BasicEPS',
      clickEmitter: true
    },
    {
      format: true,
      label: `每股净资产`,
      key: 'NAPS',
      clickEmitter: true
    },
    {
      format: true,
      label: `营业收入同比增长率(%)`,
      key: 'OperatingRevenueGrowRate',
      clickEmitter: true
    },
    {
      format: true,
      label: `净利润同比增长率`,
      key: 'NetProfitGrowRate',
      clickEmitter: true
    },
    {
      format: true,
      label: `净资产收益率_摊薄（%）`,
      key: 'ROE',
      clickEmitter: true
    },
    {
      format: true,
      label: `利润表`,
      key: '$type'
    },
    {
      format: true,
      label: `营业收入(元)`,
      key: 'OperatingReenue',
      clickEmitter: true
    },
    {
      format: true,
      label: `营业利润(元)`,
      key: 'OperatingProfit',
      clickEmitter: true
    },
    {
      format: true,
      label: `净利润(元)`,
      key: 'NetProfit',
      clickEmitter: true
    },
    {
      format: true,
      label: `资产负债表`,
      key: '$type'
    },
    {
      format: true,
      label: `资产总计(元)`,
      key: 'TotalAssets',
      clickEmitter: true
    },
    {
      format: true,
      label: `负债合计(元)`,
      key: 'TotalLiability',
      clickEmitter: true
    },
    {
      format: true,
      label: `所有者权益合计(元)`,
      key: 'TotalShareholderEquity',
      clickEmitter: true
    },
    {
      format: true,
      label: `现金流量表`,
      key: '$type'
    },
    {
      format: true,
      label: `经营活动产生的现金流量净额(元)`,
      key: 'NetOperateCashFlow',
      clickEmitter: true
    },
    {
      format: true,
      label: `投资活动产生的现金流量净额(元)`,
      key: 'NetInvestCashFlow',
      clickEmitter: true
    },
    {
      format: true,
      label: `筹资活动产生的现金流量净额(元)`,
      key: 'NetFinanceCashFlow',
      clickEmitter: true
    },
    {
      format: true,
      label: `现金及现金等价物净增加额(元)`,
      key: 'CashEquialentIncrease',
      clickEmitter: true
    },
  ]
  indicatorSource: Observable<any>;
  tabEmitter = new BehaviorSubject('all')
  lineChartSource: Observable<any>;
  lineChartEmitter = new BehaviorSubject(this.indicatorHeader[2])

  constructor (
    private router: ActivatedRoute,
    private f10Service: F10Service
  ) {}

  ngOnInit () {
    // 获取股票代码
    this.routerParamsStream = this.router.parent.parent.params.map(params => params["id"]).filter(id => !!id).map(id => {
      let stock = {
        symbol: (<string>id).replace("_", ".")
      };
      return stock
    })

    let mainIndexes = this.routerParamsStream
      .switchMap(stock => this.f10Service.getMainindexes(stock.symbol))
      .map(data => data.map(d => ({
        ...d,
        EndDate: removeHMS(d.EndDate)
      })).sort(compare('EndDate', 'des')))
      .publish().refCount();

    this.indicatorSource = mainIndexes
      .switchMap(data => {
        return this.tabEmitter
          .map(type => {
            if (type === 'all') {
              return {
                type: type,
                data: [...data]
              }
            } else {
              let timeExp = new RegExp(`\\d{4}-${type}-\\d{2}`, 'g')
              return {
                type: type,
                data: data.filter((d) => {
                  return timeExp.test(d.EndDate)
                })
              }
            }
          })
      })

    this.lineChartSource = this.indicatorSource
      // .do(data => console.log('%c 图表数据：', 'color: #f00', data))
      .map(data => ({
        ...data,
        data: data.data.reverse()  // => 绘图要求日期从旧到新
      }))
      .switchMap(rawData => {
        return this.lineChartEmitter
          .distinctUntilChanged()
          .map(chartType => {
            let labels = []
            let data = []
            rawData.data.forEach(d => {
              labels = [...labels, d[this.indicatorHeader[0].key]]
              data = [...data, parseFloat(d[chartType.key])]
            });
            return {
              type: 'line',
              data: {
                labels: [...labels],
                datasets: [{
                  label: chartType.label,
                  backgroundColor: basicChartColors[0],
                  borderColor: basicChartColors[0],
                  data: [...data],
                  fill: false,
                  pointRadius: 5,
                  borderJoinStyle: 'round'
                }]
              },
              options: {
                responsive: true,
                maintainAspectRatio: false,
                // spanGaps: true, // 中间缺点的时候是否需要忽略该点平滑连接
                elements: {
                  line: {
                    tension: 0.000001
                  }
                },
                title:{
                  display:true,
                  text: this.reportsDict[rawData.type],
                  padding: 7
                },
                tooltips: {
                  mode: 'index',
                  intersect: false,
                  callbacks: {
                    // use the label callback to change label
                    label: (tooltipItems, data, all) => {
                      let labelVal = optimizeUnit(Math.abs(tooltipItems.yLabel))
                      let labelTitle = data.datasets[tooltipItems.datasetIndex].label
                      return !isNaN(parseFloat(labelVal)) && parseFloat(labelVal) !== 0
                        ? tooltipItems.yLabel > 0
                          ? `${labelTitle}: ${labelVal}`
                          : `${labelTitle}: -${labelVal}`
                        : `${labelTitle}: --`
                      return 
                    }
                  }
                },  
                hover: {
                  mode: 'nearest',
                  intersect: true
                },
                scales: {
                  xAxes: [{
                    display: true,
                    scaleLabel: {
                      display: false,
                      labelString: 'Month'
                    }
                  }],
                  yAxes: [{
                    ticks: {
                      callback: (label, index, all) => {
                        let newVal = (all[0] - all[all.length - 1]) > 5 ? Math.round(Math.abs(label)) : Math.abs(label).toFixed(2)
                        let labelVal = optimizeUnit(newVal)
                        return label >= 0
                          ? labelVal
                          : `-${labelVal}`
                      }
                    }
                  }]
                }
              }
            }
          })
      })
      // .do(data => console.log('%c 曲线图数据：', 'color: #f00', data))
  }

  tabToggle (event) {
    this.timer = scroll(`segment-container`, event, this.timer);
  }

  tabelToggle (event) {
    this.tabEmitter.next(event)
  }

  toggleChart (payload) {
    this.lineChartEmitter.next(payload)
  }

  formatVal (value) {
    let val = parseFloat(value)
    return !isNaN(val) ? Math.floor(val / 10000) : val
  }
}